'''
Company: TWL
Author: xue jian
Email: xuejian@kanzhun.com
Date: 2020-11-24 09:44:48
'''
#
# @lc app=leetcode.cn id=222 lang=python3
#
# [222] 完全二叉树的节点个数
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0
        level=0
        move=root
        while move:
            level+=1
            move=move.left
        left, right=1<<(level-1), (1<<level) -1
        def exist(med):
            move=root
            bits=1<<(level-2)
            while move and bits>0:
                if bits&med:
                    move=move.right
                else:
                    move=move.left
                bits>>=1
            return True if move else False

            
        while left<right:
            med = (left+right+1)//2
            # print(med, left, right)
            if exist(med):
                left=med
            else:
                right=med-1
        return left
# @lc code=end

